//
//  CHSViewController.m
//  CAIUpgradeManager
//
//  Created by 海参 on 07/16/2021.
//  Copyright (c) 2021 海参. All rights reserved.
//

#import "CHSViewController.h"
#import <ZXUpgradeManager/CAIUpgradeManager.h>
#import "CHSAppDelegate.h"
#import <Masonry/Masonry.h>
#import <ZXMBProgressHUD/ZXMBProgressHUD.h>


@interface CHSViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (atomic, copy) NSArray *dataArray;
@property (nonatomic, assign) BOOL isWillUpdate;

@end

@implementation CHSViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"测试";
    [self setUI];
    [self addMas];
    [self setData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self test];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
}



- (void)addMas{

    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {      make.left.mas_equalTo(self.view.mas_left).with.offset(15);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

#pragma mark - Data

- (void)setData
{
    NSArray *sectionArr = @[
        @{
            @"section":@"selector0",
            @"sectionTitle":@"刚进页面就检查新版本",
            @"list":@[
              @{
                  @"tag":@"checkResult",
                  @"title":@"检查新版本结果"
              },
        ]},
        @{
            @"section":@"selector1",
            @"sectionTitle":@"根据传model请求检查版本更新",
            @"list":@[
              @{
                  @"tag":@"model_ui_grey1",
                  @"title":@"带默认UI弹窗样式,可配置外观。有灰度新版本，跳转灰度中间页，再跳转到testFlight"
              },
              @{
                  @"tag":@"model_ui_grey2",
                  @"title":@"带默认UI弹窗样式,可配置外观。有灰度新版本，没有配置灰度中间页，则直接跳转到testFlight"
              },
              @{
                  @"tag":@"model_ui_store1",
                  @"title":@"带默认UI弹窗样式,可配置外观。没灰度，有应用市场新版本：强制更新"
              },
              @{
                  @"tag":@"model_ui_store2",
                  @"title":@"带默认UI弹窗样式,可配置外观。没灰度，有应用市场新版本：检查苹果itunes后更新"
              },
              @{
                  @"tag":@"model_noUI",
                  @"title":@"没有UI弹窗样式"
              },
             
        ]},
        @{
            @"section":@"selector2",
            @"sectionTitle":@"根据业务请求检查版本更新：依赖业务请求",
            @"list":@[
              @{
                  @"tag":@"ui-requestUIConfig",
                  @"title":@"请求业务接口检查版本是否有更新，带默认UI弹窗样式"
              },
        ]},
        @{
            @"section":@"selector3",
            @"sectionTitle":@"只itunes检查新版本带UI",
            @"list":@[
              @{
                  @"tag":@"ui-itunes",
                  @"title":@"itunes检查新版本"
              },
        ]},
    ];
    self.dataArray = sectionArr;
}

- (void)requestData
{
    
}


#pragma mark -

- (UITableView *)tableView
{
    if (!_tableView)
    {
        UITableView *view = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        view.backgroundColor = self.view.backgroundColor;
        view.delegate = self;
        view.dataSource = self;
//        view.separatorStyle = UITableViewCellSeparatorStyleNone;
        view.showsVerticalScrollIndicator = NO;
        [view registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
        view.estimatedRowHeight = 87;
        view.rowHeight = UITableViewAutomaticDimension;
        if (@available(iOS 15.0, *)) {
            view.sectionHeaderTopPadding = 0;
        } else {
            // Fallback on earlier versions
        }
        _tableView = view;
    }
    return _tableView;
}

#pragma mark - TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSDictionary *dic = [self.dataArray objectAtIndex:section];
    NSArray *list = [dic objectForKey:@"list"];
    return list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = [NSString stringWithFormat:@"刚进页面检查新版本结果：%@",@(self.isWillUpdate)];
        return cell;
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.section];
    NSArray *list = [dic objectForKey:@"list"];
    NSDictionary *rowDic = [list objectAtIndex:indexPath.row];
    NSString *value = [rowDic objectForKey:@"title"];
    cell.textLabel.text = value;
    cell.textLabel.numberOfLines = 0;
    return cell;
}

///不支持换行的
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSDictionary *dic =  [self.dataArray objectAtIndex:section];
    NSString *title = [dic objectForKey:@"sectionTitle"];
    return title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return tableView.estimatedSectionHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.section];
    NSArray *list = [dic objectForKey:@"list"];
    NSDictionary *rowDic = [list objectAtIndex:indexPath.row];
    NSString *tag = [rowDic objectForKey:@"tag"];
    if ([tag isEqualToString:@"model_ui_grey1"]) {
        [self modelCheckWithGreyUpdate1];
    }
    else if ([tag isEqualToString:@"model_ui_grey2"]) {
        [self modelCheckWithGreyUpdate2];
    }
    else if ([tag isEqualToString:@"model_ui_store1"]) {
        [self modelCheckWithStoreUpdate1];
    }
    else if ([tag isEqualToString:@"model_ui_store2"]) {
        [self modelCheckWithStoreUpdate2];
    }
    else if ([tag isEqualToString:@"model_noUI"]) {
        [self modelCheckWithNoUI];
    }
    else if ([tag isEqualToString:@"ui-requestUIConfig"]){
        [self requestCheckWithConfigueUI];
    }
    else if ([tag isEqualToString:@"ui-itunes"]){
        [self itunesCheckUpdate];
    }
    
}


///默认UI，有灰度更新
- (void)modelCheckWithGreyUpdate1
{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    model.versionNew = @"2.2.0";
    model.isForceUpdate = NO;
    model.isHaveNewVersion = YES;
    model.isGrey = YES;
    model.middleUrl = @"https://g.520chs.com/mob_h5/public/#/gray_update?_nativeContainer=1";
    model.title = @"发现新版本V2.2.0";
    model.updateDescription = @"增加库存模块：入库、出库、盘点。\n其它细节优化";
    model.testFlightUrl = @"https://testflight.apple.com/join/EKXlMaaW";
    //    model.itunesCheckUrl = @"http://itunes.apple.com/cn/lookup?id=1512313756";
    //    model.appStoreUrl = @"https://itunes.apple.com/us/app/id1512313756";
    //    model.isItunesCheck = NO;
    [CAIUpgradeManager checkUpdateWithUIWithModel:model configueUI:nil result:^(BOOL isHaveNewVersion) {
        
    } needGreyMiddlePageAction:^(CAIClientVoModel * _Nonnull model, NSString * _Nonnull middleUrl, id  _Nonnull responseObject) {
        
    }];
}

///默认UI，有灰度更新
- (void)modelCheckWithGreyUpdate2
{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    model.versionNew = @"2.2.0";
    model.isForceUpdate = NO;
    model.isHaveNewVersion = YES;
    model.isGrey = YES;
    //    model.middleUrl = @"https://g.520chs.com/mob_h5/public/#/gray_update?_nativeContainer=1";
    model.title = @"发现新版本V2.2.0";
    model.updateDescription = @"增加库存模块：入库、出库、盘点。\n其它细节优化";
    //    model.itunesCheckUrl = @"http://itunes.apple.com/cn/lookup?id=1512313756";
    //    model.appStoreUrl = @"https://itunes.apple.com/us/app/id1512313756";
    model.testFlightUrl = @"https://testflight.apple.com/join/EKXlMaaW";
    //    model.isItunesCheck = NO;
    [CAIUpgradeManager checkUpdateWithUIWithModel:model configueUI:nil result:^(BOOL isHaveNewVersion) {
        
    } needGreyMiddlePageAction:^(CAIClientVoModel * _Nonnull model, NSString * _Nonnull middleUrl, id  _Nonnull responseObject) {
        
    }];
}


///默认UI，store有新版本，强制更新
- (void)modelCheckWithStoreUpdate1{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    model.versionNew = @"2.2.0";
    model.isForceUpdate = YES;
    model.isHaveNewVersion = YES;
    model.isGrey = NO;
    //    model.middleUrl = @"https://g.520chs.com/mob_h5/public/#/gray_update?_nativeContainer=1";
    model.title = @"发现新版本V2.2.0";
    model.updateDescription = @"增加库存模块：入库、出库、盘点。\n其它细节优化";
    model.itunesCheckUrl = @"http://itunes.apple.com/cn/lookup?id=1512313756";
    model.appStoreUrl = @"https://itunes.apple.com/us/app/id1512313756";
    model.testFlightUrl = @"https://testflight.apple.com/join/EKXlMaaW";
    model.isItunesCheck = NO;
    [CAIUpgradeManager checkUpdateWithUIWithModel:model configueUI:nil result:^(BOOL isHaveNewVersion) {
        
    } needGreyMiddlePageAction:^(CAIClientVoModel * _Nonnull model, NSString * _Nonnull middleUrl, id  _Nonnull responseObject) {
        
    }];
}

///默认UI，store有新版本，非强制更新
- (void)modelCheckWithStoreUpdate2{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    model.versionNew = @"2.2.0";
    model.isForceUpdate = NO;
    model.isHaveNewVersion = YES;
    model.isGrey = NO;
    //    model.middleUrl = @"https://g.520chs.com/mob_h5/public/#/gray_update?_nativeContainer=1";
    model.title = @"发现新版本V2.2.0";
    model.updateDescription = @"增加库存模块：入库、出库、盘点。\n其它细节优化";
    model.itunesCheckUrl = @"http://itunes.apple.com/cn/lookup?id=1512313756";
    model.appStoreUrl = @"https://itunes.apple.com/us/app/id1512313756";
    model.testFlightUrl = @"https://testflight.apple.com/join/EKXlMaaW";
    model.isItunesCheck = YES;
    [CAIUpgradeManager checkUpdateWithUIWithModel:model configueUI:nil result:^(BOOL isHaveNewVersion) {
        
    } needGreyMiddlePageAction:^(CAIClientVoModel * _Nonnull model, NSString * _Nonnull middleUrl, id  _Nonnull responseObject) {
        
    }];
}


- (void)modelCheckWithNoUI{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    model.versionNew = @"2.2.0";
    model.isForceUpdate = NO;
    model.isHaveNewVersion = YES;
    model.isGrey = NO;
    //    model.middleUrl = @"https://g.520chs.com/mob_h5/public/#/gray_update?_nativeContainer=1";
    model.updateDescription = @"增加库存模块：入库、出库、盘点。\n其它细节优化";
    model.itunesCheckUrl = @"http://itunes.apple.com/cn/lookup?id=1512313756";
    model.appStoreUrl = @"https://itunes.apple.com/us/app/id1512313756";
    model.testFlightUrl = @"https://testflight.apple.com/join/EKXlMaaW";
    model.isItunesCheck = YES;
    [CAIUpgradeManager checkUpdateWithModel:model result:^(CHSClientPackageModel * _Nonnull model, BOOL isHaveNewVersion) {
        [MBProgressHUD zx_showSuccess:[NSString stringWithFormat:@"是否有新版本：%@",@(isHaveNewVersion)]];
    }];
}



///自动检查
- (void)test{
    __weak __typeof(&*self)weakSelf = self;
    
    [CAIUpgradeManager checkUpdateGeneralWithResult:^(CHSClientPackageModel * _Nonnull model, BOOL isHaveNewVersion) {
        weakSelf.isWillUpdate = isHaveNewVersion;
        [weakSelf.tableView reloadData];
        
    } failureBlock:^(id _Nonnull meta) {
        
    }];
}




- (void)requestCheckWithConfigueUI
{
    CAIUpgradeGeneralUIConfig *config = [CAIUpgradeGeneralUIConfig new];
    config.doButtonCornerType = UpgradeDoButtonCornerTypeRound;
    [CAIUpgradeManager checkUpdateWithUIWithConfigueUI:config result:^(BOOL isHaveNewVersion) {
        
    } needGreyMiddlePageAction:^(CAIClientVoModel * _Nonnull model,NSString *middleUrl,id  _Nonnull responseObject) {
        
    } failureBlock:^(id _Nonnull meta) {
        //            [MBProgressHUD zx_showError:@"错误"];
    }];
}

- (void)itunesCheckUpdate{
    CAIClientVoModel *model = [CAIClientVoModel new];
    model.appId = @"1512313756";
    [CAIUpgradeManager checkOnlyItunesWithUIWithModel:model checkResult:^(BOOL isHaveNewVersion) {
            
        } failure:^(NSError * _Nonnull error) {
            
        }];
}


@end

